/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable react/jsx-no-bind */
/* eslint-disable no-shadow */
import React, { useState } from 'react';
import { useAntdTable, useDebounceFn } from 'ahooks';
import { Form, Table, Input, Button, message, Row, Col, Popconfirm } from 'antd';
import { frameEdit, getSiteScanList, siteScanAdd, siteScanEdit } from '@/services/setup';
import SiteModal from '@/components/_pages/Post/Setup/SiteScanManage/SiteModal';
import { setLStorage } from '@/utils/utils';

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 18 },
  },
};

const FormItem = Form.Item;

const SiteScanManage = props => {
  const { form } = props;
  const { getFieldDecorator, validateFields } = form;

  const [openType, setOpenType] = useState('');
  const [submitting, setSubmitting] = useState(false);

  const getTableList = async (params, formData) => {
    const { current, pageSize } = params;

    const result = await getSiteScanList({
      page: current,
      pageSize,
      ...formData,
    });

    return result;
  };

  const { tableProps, search, loading } = useAntdTable(getTableList, {
    defaultPageSize: 20,
    form,
  });

  const { run: onSubmit } = useDebounceFn(
    e => {
      e.preventDefault();
      validateFields(async err => {
        if (err) return;
        search.submit();
      });
    },
    {
      wait: 300,
      leading: true,
      trailing: false,
    },
  );

  const handleOpenAuth = (status, id) => {
    siteScanEdit({
      id,
      status: status == 1 ? 0 : 1,
    }).then(res => {
      const { code, msg } = res || {};
      if (code == 0) {
        search.reset();
      } else {
        message.error(msg);
      }
    });
  };

  const columns = [
    {
      width: 100,
      align: 'center',
      title: 'id',
      dataIndex: 'id',
    },
    {
      width: 200,
      align: 'center',
      title: '快递员电话',
      dataIndex: 'username',
    },
    {
      width: 150,
      align: 'center',
      title: '快递员姓名',
      dataIndex: 'realname',
    },
    {
      width: 150,
      align: 'center',
      title: '更新时间',
      dataIndex: 'update_at',
    },
    {
      width: 200,
      align: 'center',
      title: '状态',
      dataIndex: 'status',
      render: status => (status == 0 ? '禁用' : '启用'),
    },
    {
      width: 150,
      align: 'center',
      title: '操作',
      render: (_, record) => {
        const { status, id } = record;
        return (
          <Row type="flex" justify="space-around">
            <Col>
              <Popconfirm
                onConfirm={handleOpenAuth.bind(null, status, id)}
                title={`确认${status == 1 ? '禁用' : '启用'}？`}
              >
                <a>{status == 1 ? '禁用' : '启用'}</a>
              </Popconfirm>
            </Col>
          </Row>
        );
      },
    },
  ];

  const handelOpenModal = type => {
    setOpenType(type);
  };

  const submitFn = (fetchFn, params) =>
    new Promise((resolve, reject) => {
      fetchFn(params)
        .then(res => {
          if (res.code == 0) {
            resolve();
          } else {
            message.error(res.msg);
            reject();
          }
        })
        .catch(reject);
    });

  const handleOnModalOk = (value, type) => {
    const { input } = value || {};
    if (!type) {
      message.error('缺失类型');
      return;
    }
    const fetchFn = type == 'add' ? siteScanAdd : frameEdit;
    const params =
      type == 'add'
        ? {
            phone: input,
          }
        : {
            frame_num: input,
          };
    setSubmitting(true);
    submitFn(fetchFn, params)
      .then(() => {
        if (type == 'edit') {
          setLStorage('frame_num', params);
        }
        search.reset();
        setOpenType('');
        setSubmitting(false);
      })
      .catch(() => {
        setSubmitting(false);
      });
  };

  return (
    <div>
      <Form layout="inline" {...formItemLayout} style={{ marginBottom: 24 }}>
        <FormItem>
          {getFieldDecorator('search')(
            <Input allowClear placeholder="输入快递员手机号搜索" style={{ width: 250 }} />,
          )}
        </FormItem>
        <FormItem>
          <Button type="primary" onClick={onSubmit} loading={loading}>
            查询
          </Button>
        </FormItem>
        <FormItem>
          <Button type="primary" onClick={handelOpenModal.bind(null, 'add')} loading={loading}>
            新增操作员
          </Button>
        </FormItem>
        <FormItem>
          <Button type="primary" onClick={handelOpenModal.bind(null, 'edit')} loading={loading}>
            货架设置
          </Button>
        </FormItem>
      </Form>
      <Table scroll={{ x: 800 }} rowKey="id" loading={loading} columns={columns} {...tableProps} />
      <SiteModal
        confirmLoading={submitting}
        type={openType}
        visible={!!openType}
        onOk={handleOnModalOk}
        onCancel={() => {
          setOpenType('');
        }}
      />
    </div>
  );
};

export default Form.create()(SiteScanManage);
